#!/usr/bin/env python
# -*- coding: utf-8 -*-

import threading
import SocketServer
import MysqlUtils
import Config
import time


class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    """
    请求处理handler
    """
    def handle(self):
        address = self.client_address
        cur_thread = threading.current_thread()
        print time.ctime(), cur_thread.name, "...connected from:", address
        while True:
            data = self.request.recv(Config.BUFFER_SIZE)
            if not data or data.find('s,') == -1 or data.find(',$') == -1:
                print time.ctime(), cur_thread.name, self.client_address, "client quit"
                break
            print time.ctime(), cur_thread.name, self.client_address, data
            if not address[0].startswith('211'):
                self.request.sendall('failure')
            # 解析数据
            data = data.split(',')
            cno = data[1]
            flowmeter_id = data[2]
            add_time = data[3]
            d1 = data[4]
            d2 = data[5]
            d3 = data[6]
            d4 = data[7]
            d5 = data[8]
            d6 = data[9]
            # 写入数据
            # 先查询是否已经存在站好和ID
            db = MysqlUtils.MysqlHelper()
            id_count = db.query("SELECT COUNT(id) as id_count FROM natgas_other1flowmeterreg WHERE cno='%s' and flowmeter_id='%s'" % (cno, flowmeter_id))[0]['id_count']
            if id_count == 0:
                db.dml("INSERT INTO natgas_other1flowmeterreg(cno, flowmeter_id, add_time) "
                       "VALUES('%s', '%s', now())"
                       % (cno, flowmeter_id))
            # 根据cno和flowmeter_id查询流量计的ID
            fid = db.query(
                "SELECT id FROM natgas_other1flowmeterreg WHERE cno='%s' and flowmeter_id='%s'"
                %
                (cno, flowmeter_id)
            )[0]['id']
            db.dml(
                "INSERT INTO natgas_other1flowmeterdata(flowmeter_type, d1, d2, d3, d4, d5, d6, add_time, flowmeter_id) "
                "VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')"
                %
                ('3', d1, d2, d3, d4, d5, d6, add_time, fid)
            )
            self.request.sendall('success')


class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    """
    多线程处理的TCP服务器
    """
    # 允许重用地址
    allow_reuse_address = True

if __name__ == "__main__":
    server = ThreadedTCPServer((Config.SERVER_HOST, Config.SERVER_PORT), ThreadedTCPRequestHandler)
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.start()
    print 'Bind TCP on 9999...'
